package com.hooya.fa.eu.biz.service.impl;

import cn.hutool.http.HttpRequest;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hooya.fa.eu.biz.dao.entity.Pl2cInvoices;
import com.hooya.fa.eu.biz.dao.mapper.Pl2cInvoicesMapper;
import com.hooya.fa.eu.biz.dao.repository.Pl2cInvoicesRepository;
import com.hooya.fa.eu.biz.service.Pl2cInvoicesService;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author LiHongLiang
 * @since 2024-12-09
 */
@Slf4j
@Service
@DS("fa_eu")
@RefreshScope
@AllArgsConstructor
public class Pl2cInvoicesServiceImpl extends ServiceImpl<Pl2cInvoicesMapper, Pl2cInvoices> implements Pl2cInvoicesService {

    private final Pl2cInvoicesMapper pl2cInvoicesMapper;

    @Resource
    private final Pl2cInvoicesRepository pl2cInvoicesRepository;

    @Override
    public void saveInvoicesList() {
        QueryWrapper<Pl2cInvoices> wrapper = new QueryWrapper();
        wrapper.select("MAX(CAST(invoice_id as UNSIGNED)) as id");
        Pl2cInvoices invoices = pl2cInvoicesMapper.selectOne(wrapper);
        Long id = null;
        int init = 0;
        if (invoices == null) {
            id = Long.valueOf(1);
        } else {
            id = invoices.getId();
            init = 1;
        }
//        System.out.println("id:"+id);

        HashMap<String, Object> paramMap = new HashMap<>();
        paramMap.put("method", "getInvoices");
        paramMap.put("parameters", "{\"id_from\": " + id + "}");
        HttpRequest request = HttpRequest.post("https://api.baselinker.com/connector.php")
                .header("X-BLToken", "2915-20165-2AXQGXZURQVTNR49J28LZIXKBMOC8H3ABH9SDFNFN5D1U91OXX7P7Q9FOEQV8C98")
                .form(paramMap).timeout(50000);

        JSONObject response = JSON.parseObject(request.execute().body());
//        System.out.println("status:"+response.getString("status"));
        if ("SUCCESS".equals(response.getString("status"))) {
            List jsonList = response.getJSONArray("invoices");
            List<Pl2cInvoices> list = new ArrayList();
            for (int i = init; i < jsonList.size(); i++) {
                JSONObject obj = (JSONObject) JSONObject.toJSON(jsonList.get(i));
                Pl2cInvoices pl2cInvoices = new Pl2cInvoices();
                pl2cInvoices.setInvoiceId(obj.getString("invoice_id"));
                pl2cInvoices.setOrderId(obj.getString("order_id"));
                pl2cInvoices.setType(obj.getString("type"));
                pl2cInvoices.setNumber(obj.getString("number"));
                pl2cInvoices.setYear(obj.getInteger("year"));
                pl2cInvoices.setMonth(obj.getInteger("month"));
                pl2cInvoices.setSubId(obj.getInteger("sub_id"));
                pl2cInvoices.setPostfix(obj.getString("postfix"));
                pl2cInvoices.setDateAdd(obj.getInteger("date_add"));
                pl2cInvoices.setDateSell(obj.getInteger("date_sell"));
                pl2cInvoices.setDatePayTo(obj.getInteger("date_pay_to"));
                pl2cInvoices.setCurrency(obj.getString("currency"));
                pl2cInvoices.setTotalPriceBrutto(obj.getDouble("total_price_brutto"));
                pl2cInvoices.setTotalPriceNetto(obj.getDouble("total_price_netto"));
                pl2cInvoices.setInvoiceFullname(obj.getString("invoice_fullname"));
                pl2cInvoices.setInvoiceCompany(obj.getString("invoice_company"));
                pl2cInvoices.setInvoiceNip(obj.getString("invoice_nip"));
                pl2cInvoices.setInvoiceAddress(obj.getString("invoice_address"));
                pl2cInvoices.setInvoiceCity(obj.getString("invoice_city"));
                pl2cInvoices.setInvoicePostcode(obj.getString("invoice_postcode"));
                pl2cInvoices.setInvoiceCountry(obj.getString("invoice_country"));
                pl2cInvoices.setInvoiceCountryCode(obj.getString("invoice_country_code"));
                pl2cInvoices.setSeller(obj.getString("seller"));
                pl2cInvoices.setPayment(obj.getString("payment"));
                pl2cInvoices.setCorrectingToInvoiceId(obj.getInteger("correcting_to_invoice_id"));
                pl2cInvoices.setCorrectingReason(obj.getString("correcting_reason"));
                pl2cInvoices.setCorrectingItems(obj.getBoolean("correcting_items"));
                pl2cInvoices.setCorrectingData(obj.getBoolean("correcting_data"));
                pl2cInvoices.setExternalInvoiceNumber(obj.getString("external_invoice_number"));
                pl2cInvoices.setExternalId(obj.getString("external_id"));
                pl2cInvoices.setExchangeCurrency(obj.getString("exchange_currency"));
                pl2cInvoices.setExchangeRate(obj.getString("exchange_rate"));
                pl2cInvoices.setExchangeDate(obj.getString("exchange_date"));
                pl2cInvoices.setExchangeInfo(obj.getString("exchange_info"));
                pl2cInvoices.setCreateTime(LocalDateTime.now());
                list.add(pl2cInvoices);
            }
            this.saveBatch(list);
            log.info(LocalDateTime.now() + "：从" + id + "开始取数据已完成");
        }

    }
}
